package com.woniuxy.util;


import com.woniuxy.core.exception.WoniuxyException;
import lombok.Data;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

//互亿无线短信工具类
@ConfigurationProperties(prefix = "sms.huyi")
@Component
@Data
public class MySmsUtil {
    private String api;
    private String account;
    private String password;

    public String send(String mobile) throws Exception {
        // 随机生成验证码
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String content = new String("您的验证码是：" + code + "。请不要把验证码泄露给其他人。");
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建http对象
        HttpPost httpPost = new HttpPost(api);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000).setSocketTimeout(6000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("account", account);
        params.put("password", password);
        params.put("mobile", mobile);
        params.put("content", content);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<Entry<String, String>> entrySet = params.entrySet();
        for (Entry<String, String> entry : entrySet) {
            nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        // 设置到请求的http对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        // 封装请求参数
        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        String resp = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        Document doc = DocumentHelper.parseText(resp);
        Element root = doc.getRootElement();
        String result = root.elementText("code");
        if ("2".equals(result)) {
            return code+"";
        } else {
            // 抛出自定义异常
            throw new WoniuxyException(500,"短信发送失败");
        }
    }
}
